package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ISkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.vo.SkuStockVo;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-24
 */
@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SkuStock::getSkuId, skuId).select(SkuStock::getAvailableNum, SkuStock::getSaleNum);
        SkuStock skuStock = baseMapper.selectOne(queryWrapper);
        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        skuStockVo.setSaleNum(skuStock.getSaleNum());
        skuStockVo.setSkuId(skuId);
        return skuStockVo;
    }

    /**
     * 检查库存并锁定库存
     * @param orderNo 订单号
     * @param skuLockVoList 下单的商品信息
     * @return 若返回""则代表锁定成功 其他皆为失败
     */
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        // 遍历skuLockVoList 查看每件商品库存是否足够
        for (SkuLockVo skuLockVo : skuLockVoList) {
            // 获取商品id
            Long skuId = skuLockVo.getSkuId();
            // 获取购买数量
            Integer num = skuLockVo.getSkuNum();
            // 获取商品库存
            SkuStock skuStock = baseMapper.check(skuId, num);
            // 判断库存是否足够
            skuLockVo.setHaveStock(null != skuStock);
        }

        // 只要有一件商品库存不足
        if(!skuLockVoList.stream().allMatch(SkuLockVo::isHaveStock)){
            // 找出库存不足的商品
            List<SkuLockVo> noStockList = skuLockVoList.stream().filter(skuLockVo -> !skuLockVo.isHaveStock()).toList();
            StringBuffer errorMsg = new StringBuffer();
            for (SkuLockVo skuLockVo : noStockList) {
                LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SkuStock::getSkuId, skuLockVo.getSkuId()).select(SkuStock::getAvailableNum);
                Integer availableNum = baseMapper.selectOne(queryWrapper).getAvailableNum();
                errorMsg.append(skuLockVo.getSkuName()).append("库存不足，请重新下单！").append("剩余库存为：").append(availableNum);
            }
            return errorMsg.toString();
        }else {
            for (SkuLockVo skuLockVo : skuLockVoList) {
                // 锁定库存
                baseMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }
        }
        // 如果所有商品都锁定成功的情况下，需要缓存锁定信息到redis。以方便将来解锁库存 或者 减库存
        String dataKey = "sku:lock:data:" + orderNo;
        redisTemplate.opsForValue().set(dataKey, skuLockVoList);
        return "";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlock(String orderNo) {
        // 幂等性处理
        Boolean isFirst = redisTemplate.opsForValue().setIfAbsent("sku:unlock:" + orderNo, orderNo,1, TimeUnit.MINUTES);
        if(!isFirst){
            return;
        }
    // 获取锁定库存的缓存信息
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if(!CollectionUtils.isEmpty(skuLockVoList)){
            // 解锁库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                baseMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }
        }

        // 解锁库存之后，删除锁定库存的缓存
        redisTemplate.delete(dataKey);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void minus(String orderNo) {

        //幂等性处理
        String key = "sku:minus:" + orderNo;
        Boolean isFirst = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.MINUTES);
        if(!isFirst) return;

        // 获取锁定库存的缓存信息
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if(!CollectionUtils.isEmpty(skuLockVoList)){
            // 减库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                baseMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }
        }

        // 扣减库存之后，删除锁定库存的缓存
        redisTemplate.delete(dataKey);
    }
}
